﻿ namespace SCCM_Client_Injector_2014
 {
    using Microsoft.ConfigurationManagement.ManagementProvider;
    using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;
    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;

    internal class DuplicateCheck
    {

        private WqlConnectionManager connection;

        public void DeleteDuplicateClientfromSCCM(WqlConnectionManager WMIconnection)
        {
            this.connection = WMIconnection;
        }


        public int FindResourceID(string Client)
        {
            int integerValue = 0;
            string query = "SELECT ResourceId FROM SMS_R_System WHERE NetbiosName ='" + Client + "'";
            foreach (IResultObject collections in this.connection.QueryProcessor.ExecuteQuery(query))
            {
                integerValue = collections["ResourceID"].IntegerValue;
                Application.DoEvents();
            }
            return integerValue;
        }

        public void RemoveClient(CheckedListBox checkedListBoxCollectionsMembership, string Client)
        {
            int num = this.FindResourceID(Client);
            if (num != 0)
            {
                foreach (string str in checkedListBoxCollectionsMembership.CheckedItems)
                {
                    string query = "SELECT * FROM SMS_Collection Where Name ='" + str + "'";
                    foreach (IResultObject collections in this.connection.QueryProcessor.ExecuteQuery(query))
                    {
                        IResultObject instance = this.connection.GetInstance("SMS_Collection.CollectionID='" + collections["CollectionID"].StringValue + "'");
                        IResultObject collectionRule = this.connection.CreateEmbeddedObjectInstance("SMS_CollectionRuleDirect");
                        collectionRule["ResourceID"].IntegerValue = num;
                        Dictionary<string, object> methodParameters = new Dictionary<string, object>();
                        methodParameters.Add("collectionRule", collectionRule);
                        instance.ExecuteMethod("DeleteMemberShipRule", methodParameters);
                        Dictionary<string, object> dictionary2 = new Dictionary<string, object>();
                        dictionary2.Add("IncludeSubCollections", false);
                        instance.ExecuteMethod("RequestRefresh", dictionary2);
                    }
                    Application.DoEvents();
                }
                MessageBox.Show("Successfully removed the Client: " + Client + " from the Collections");
            }
            else
            {
                MessageBox.Show("Client: " + Client + " does not exist in SCCM.");
            }
        }
    }
}

